<template>
  <div class="app-container">
    <el-card>
      <list
        @changeCurrentPage="changeCurrentPage"
        @changePagesize="changePagesize"
        @edit="edit"
        @set="set"
      />
    </el-card>
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <main-form
        :form-data="formData"
        @submit="submit"
        @updateRtuPortDisplays="updateRtuPortDisplays"
      />
    </el-dialog>
    <set-form ref="set" />
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import List from './component/list'
import MainForm from './component/main-form'
import SetForm from './component/Set'
import CommonMixin from '@/mixin/CommonMixin'
import { getOne, updateOne, updateRtuPortDisplays } from '@/api/device'
import { removeEmptyField } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  components: {
    List,
    MainForm,
    SetForm
  },
  directives: { elDragDialog },
  mixins: [CommonMixin],
  computed: {
    ...mapGetters(['devices', 'currentDevice'])
  },
  methods: {
    set(row) {
      this.$refs.set.show(row)
    },
    submit(formData) {
      formData = removeEmptyField(formData)
      this.updateOne(formData)
    },
    updateOne(formData) {
      updateOne(formData.serialno, formData).then(res => {
        this.$message.success(res.msg)
        this.dialogVisible = false
        this._afterSubmit(formData.serialno, formData)
      })
    },
    getOne(row) {
      getOne(row.serialno).then(res => {
        this.formData = res.data
        this.dialogVisible = true
      })
    },
    _afterSubmit(serialno, formData) {
      const idx = this.devices.findIndex((val) => {
        return val.serialno === serialno
      })
      this.devices[idx] = Object.assign(this.devices[idx], formData)
    },
    async updateRtuPortDisplays(info, serialno) {
      const { msg, data } = await updateRtuPortDisplays(info, serialno)
      this.$message.success(msg)
      this.dialogVisible = false
      const deviceIdx = this.devices.findIndex((val) => {
        return val.serialno === serialno
      })
      const device = this.devices[deviceIdx]
      device['rtuPortDisplays'] = data
      // this.$store.commit('device/SET_DEVICES', this.devices)
      this.$store.commit('device/SET_DEVICE', device)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
